package com.jacken.mars.commons.mq.base.mq.consumer.impl;

import com.jacken.mars.commons.enums.MQEnum;
import com.jacken.mars.commons.mq.base.mq.consumer.ConsumerListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.dc.pr.PRError;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author wangqinag
 * @version 1.0
 * @date 2021/1/4 10:29
 */
@Component
@Slf4j
public class SaveBatchConsumerListener implements ConsumerListener {

    @Value("${rocketmq.nameServer}")
    private String nameServer;



    @Override
    //@PostConstruct
    public void init() throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(MQEnum.SAVE_BATCH_MQ.getGroup());
        consumer.setNamesrvAddr(nameServer);
        //消费模式:一个新的订阅组第一次启动从队列的最后位置开始消费 后续再启动接着上次消费的进度开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        //订阅主题和 标签（ * 代表所有标签)下信息
        consumer.subscribe(MQEnum.SAVE_BATCH_MQ.getTopic(), "*");
        //注册消费的监听 并在此监听中消费信息，并返回消费的状态信息
        consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
            // msg中只收集同一个topic，同一个tag，并且key相同的message
            // 会把不同的消息分别放置到不同的队列中
            for (Message msg : msgs) {
                //消费者获取消息 这里只输出 不做后面逻辑处理
                String body = new String(msg.getBody(), StandardCharsets.UTF_8);
                log.info("接收到消息===>" + body);
                log.info("Consumer-获取消息-主题topic为={}, 消费消息为={}", msg.getTopic(), body);
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        consumer.start();
        log.info(MQEnum.SAVE_BATCH_MQ.getTopic() + "消费者 启动成功");
    }
}
